package cn.com.common.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@AutoConfigureBefore(DynamicDataSourceAutoConfiguration.class)
@AutoConfigureAfter(SpringBootConfiguration.class)
public class DataSourcesConfig {

	@Autowired
	private DynamicDataSourceProperties properties;

	@Autowired
	private DataSource shardingDataSource;

	@Bean
	public DynamicDataSourceProvider dynamicDataSourceProvider() {
		return new AbstractDataSourceProvider() {
			@Override
			public Map<String, DataSource> loadDataSources() {
				Map<String, DataSource> dataSourceMap = new HashMap<>(2);
				
				dataSourceMap.put("sharding-year-month", shardingDataSource);
				dataSourceMap.put("sharding", shardingDataSource);
				
				dataSourceMap.put("master", shardingDataSource);
				dataSourceMap.put("oracle", shardingDataSource);
				dataSourceMap.put("sqlServer", shardingDataSource);
				dataSourceMap.put("postgresql", shardingDataSource);
				dataSourceMap.put("mysql_zn", shardingDataSource);
				dataSourceMap.put("mysql_province", shardingDataSource);
				
				return dataSourceMap;
			}
		};
	}

	@Bean
	@Primary
	public DataSource dataSource() {
		DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
		dataSource.setPrimary(properties.getPrimary());
		dataSource.setStrict(properties.getStrict());
		dataSource.setStrategy(properties.getStrategy());
		dataSource.setP6spy(properties.getP6spy());
		dataSource.setSeata(properties.getSeata());
		return dataSource;
	}

}